from flask import Blueprint, jsonify
from app.extensions import cors, csrf
from .resources.token import AuthTokenAPI
from .resources.users import UserAPI, UsersAPI, SmsAPI
from .resources.bills import BillsAPI, BillAPI
from .resources.orders import OrdersAPI, OrderAPI


bp = Blueprint('api_v1', __name__)
cors.init_app(bp)
csrf.exempt(bp)



# 获取账单
bp.add_url_rule('/bills/<int:id>', view_func=BillAPI.as_view('bill'), methods=['GET'])
bp.add_url_rule('/bills', view_func=BillsAPI.as_view('bills'), methods=['GET'])


# 获取订单
bp.add_url_rule('/orders/<int:id>', view_func=OrderAPI.as_view('order'), methods=['GET'])
bp.add_url_rule('/orders', view_func=OrdersAPI.as_view('orders'), methods=['GET'])

# 获取用户信息
bp.add_url_rule('/user', view_func=UserAPI.as_view('user'), methods=['GET', 'POST'])

# 注册用户
bp.add_url_rule('/users', view_func=UsersAPI.as_view('users'), methods=['POST', 'PUT'])

# 获取用户授权
bp.add_url_rule('/oauth/token', view_func=AuthTokenAPI.as_view('token'), methods=['POST'])

# 获取短信验证、验证验证码
bp.add_url_rule('/sms', view_func=SmsAPI.as_view('sms'), methods=['POST', 'PUT'])


@bp.errorhandler(422)
def handle_validation_error(e):
    exc = e.exc
    return jsonify(errors=exc.messages), 422


@bp.errorhandler(403)
def handle_validation2_error(e):
    return jsonify(success=False, message='权限不够')
